package com.sinog.biz.schedule;

import com.alibaba.excel.util.CollectionUtils;
import com.sinog.biz.BizApplication;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.biz.util.DataSourceCheckUtils;
import com.sinog.core.domain.AbPrisonersResultVo;
import com.sinog.core.domain.AbXiaozuResultVo;
import com.sinog.core.domain.PrisaveTemp;
import com.sinog.core.domain.PrisonerCjpg;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonerHc;
import com.sinog.core.domain.PrisonerJxjs;
import com.sinog.core.domain.PrisonerMain;
import com.sinog.core.domain.PrisonerSr;
import com.sinog.core.domain.PrisonerXjxx;
import com.sinog.core.domain.PrisonerZn;
import com.sinog.core.domain.PrisonersZyjn;
import com.sinog.core.domain.XjReceipt;
import com.sinog.core.domain.XjReceiptData;
import com.sinog.core.utilbean.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc 自建定时任务 每5分钟执行一次
 * @author wangxj
 * @date -
 */
@Slf4j
@Component
@Configuration
@ConditionalOnProperty(name = "gkzx.azbj.zj.open", havingValue = "true")
public class ZiJianSchedule {

    private JdbcTemplate zijianJdbcTemplate;
    private JdbcTemplate jdbcTemplate;

    /**
     * 描述
     */
    @Scheduled(cron = "${gkzx.azbj.zj.cron}")
    private void getLocalProvinceDataFromZijian() {
        String localCode = CodeUrlUtils.getLocalCode();
        ConfigurableApplicationContext applicationContext = BizApplication.applicationContext;
        if(!ObjectUtils.allNotNull(zijianJdbcTemplate)) {
            zijianJdbcTemplate = (JdbcTemplate)applicationContext.getBean("zijianJdbcTemplate");
        }
        //检测全部数据源是否可用
        boolean allRunning = DataSourceCheckUtils.checkRunningStatus(zijianJdbcTemplate);
        if(true){
            String sql = "SELECT sc.id,pm.pri_num as priNum,zj_state as zjstate,fqhc_state as fqhcstate,wchc_state as wchcstate,fqxj_state as fqxjstate,wcxj_state as wcxjstate FROM prisoner_main pm inner join state_cq sc on pm.pri_num = sc.pri_num where pm.nativepro = '" + localCode + "' and sc.zj_state in ('1','2','3','4') and sc.owner_province ='" + '1' + "'";
            String prisonerMainSql = "select *,p_name as pName from prisoner_main where pri_num = ?";
            String prisaveTempSql = "select * from prisave_temp where pri_num = ?";
            String prisonerFxSql = "select * from prisoner_fx where pri_num = ?";
            String prisonerSrSql = "select * from prisoner_sr where pri_num = ?";
            String prisonerZnSql = "select * from prisoner_zn where pri_num = ?";
            String prisonerHcSql = "select * from prisoner_hc where pri_num = ?";
            String prisonerJxjsSql = "select * from prisoners_jxjs where pri_num = ?";
            String prisonerZyjnSql = "select * from prisoners_zyjn where pri_num = ?";
            String xjReceiptSql = "select * from xj_receipt where pri_num = ?";
            String xjReceiptDataSql = "select * from xj_receipt_data where session_id = ?";
            String prisonerCjpgSql = "select * from prisoner_cjpg where pri_num = ?";
            String prisonerXjxxSql = "select * from prisoner_xjxx where pri_num = ?";
            String abPrisonersSql = "select * from ab_prisoners where pri_num = ?";
            String abXiaozuSql = "select * from ab_xiaozu where pri_num = ?";
            String sql1 = "";
            String sql2 = "";
            String sql3 = "";
            String sql4 = "";
            List<Map<String,Object>> maps = zijianJdbcTemplate.queryForList(sql);
            for(Map<String,Object> map : maps) {
                String priNum = (String)map.get("priNum");
                String id = (String)map.get("id");
                String zjstate = (String)map.get("zjstate");
                String fqhcstate = (String)map.get("fqhcstate");
                String wchcstate = (String)map.get("wchcstate");
                String fqxjstate = (String)map.get("fqxjstate");
                String wcxjstate = (String)map.get("wcxjstate");
                try {
                    //发起核查
                    if(StringUtils.equals(zjstate,Constants.NumberStr.NUM_STR_ONE) && StringUtils.equals(fqhcstate,Constants.NumberStr.NUM_STR_ZERO)) {
                        executezxhc(prisonerMainSql,prisaveTempSql,prisonerFxSql,prisonerSrSql,prisonerZnSql,prisonerHcSql,priNum);
                        sql1 = "update state_cq set fqhc_state='1' where id='" + id + "'";
                    }
                } catch(Exception e) {
                    //将fqhc_state设置为未抽取
                    sql1 = "update state_cq set fqhc_state='0' where id='" + id + "'";
                    log.error("发生异常:{}",e.getMessage());
                }
                try {
                    //完成核查
                    if(StringUtils.equals(zjstate,Constants.NumberStr.NUM_STR_TWO) && StringUtils.equals(wchcstate,Constants.NumberStr.NUM_STR_ZERO)) {
                        executezxhc(prisonerMainSql,prisaveTempSql,prisonerFxSql,prisonerSrSql,prisonerZnSql,prisonerHcSql,priNum);
                        sql2 = "update state_cq set wchc_state='1' where id='" + id + "'";
                    }
                } catch(Exception e) {
                    //将wchc_state设置为未抽取
                    log.error("发生异常:{}",e.getMessage());
                    sql2 = "update state_cq set wchc_state='0' where id='" + id + "'";
                }
                try {
                    //发起衔接
                    if(StringUtils.equals(zjstate,Constants.NumberStr.NUM_STR_THREE) && StringUtils.equals(fqxjstate,Constants.NumberStr.NUM_STR_ZERO)) {
                        executeZxxj(prisonerMainSql,prisaveTempSql,prisonerFxSql,prisonerSrSql,prisonerZnSql,prisonerJxjsSql,prisonerZyjnSql,xjReceiptSql,xjReceiptDataSql,prisonerCjpgSql,prisonerXjxxSql,abPrisonersSql,abXiaozuSql,prisonerHcSql,priNum,"3");
                        sql3 = "update state_cq set fqxj_state='1' where id='" + id + "'";
                    }
                } catch(Exception e) {
                    //将fqxj_state设置为未抽取
                    sql3 = "update state_cq set fqxj_state='0' where id='" + id + "'";
                    log.error("发生异常:{}",e.getMessage());
                }
                try {
                    //完成衔接
                    if(StringUtils.equals(zjstate,Constants.NumberStr.NUM_STR_FOUR) && StringUtils.equals(wcxjstate,Constants.NumberStr.NUM_STR_ZERO)) {
                        executeZxxj(prisonerMainSql,prisaveTempSql,prisonerFxSql,prisonerSrSql,prisonerZnSql,prisonerJxjsSql,prisonerZyjnSql,xjReceiptSql,xjReceiptDataSql,prisonerCjpgSql,prisonerXjxxSql,abPrisonersSql,abXiaozuSql,prisonerHcSql,priNum,"4");
                        sql4 = "update state_cq set wcxj_state='1' where id='" + id + "'";
                    }
                } catch(Exception e) {
                    //将wcxj_state设置未抽取
                    sql4 = "update state_cq set wcxj_state='0' where id='" + id + "'";
                    log.error("发生异常:{}",e.getMessage());
                }
                if(!StringUtils.equals(sql1,"")) {
                    zijianJdbcTemplate.update(sql1);
                } else if(!StringUtils.equals(sql2,"")) {
                    zijianJdbcTemplate.update(sql2);
                } else if(!StringUtils.equals(sql3,"")) {
                    zijianJdbcTemplate.update(sql3);
                } else if(!StringUtils.equals(sql4,"")) {
                    zijianJdbcTemplate.update(sql4);
                }
            }
        } else {
            log.error("检测到数据源不可用,本次执行任务失败!");
        }
    }

    /**
     * 删除撤回核查同步的记录
     */
    @Scheduled(cron = "${gkzx.azbj.zj.cron}")
    private void deleteForHcState() {
        //获取数据源
        String localCode = CodeUrlUtils.getLocalCode();
        ConfigurableApplicationContext applicationContext = BizApplication.applicationContext;
        if(!ObjectUtils.allNotNull(jdbcTemplate)) {
            jdbcTemplate = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");
        }
        if(!ObjectUtils.allNotNull(zijianJdbcTemplate)) {
            zijianJdbcTemplate = (JdbcTemplate)applicationContext.getBean("zijianJdbcTemplate");
        }
        //检测全部数据源是否可用
        boolean allRunning = DataSourceCheckUtils.checkRunningStatus(jdbcTemplate,zijianJdbcTemplate);
        if(true){
            String sql = "SELECT sc.id,pm.pri_num as priNum,zj_state as zjstate,fqhc_state as fqhcstate,wchc_state as wchcstate,fqxj_state as fqxjstate,wcxj_state as wcxjstate FROM prisoner_main pm inner join state_cq sc on pm.pri_num = sc.pri_num where pm.nativepro = '" + localCode + "' and sc.hc_state = '2' and sc.owner_province ='" + '1' + "'";
            String delPrisonerMainSql = "DELETE FROM prisoner_main WHERE pri_num = ?";
            String delPrisonerFxSql = "DELETE FROM prisoner_fx WHERE pri_num = ?";
            String delPrisonerSrSql = "DELETE FROM prisoner_sr WHERE pri_num = ?";
            String delPrisonerZnSql = "DELETE FROM prisoner_zn WHERE pri_num = ?";
            String delPrisonerHcSql = "DELETE FROM prisoner_hc WHERE pri_num = ?";
            List<Map<String,Object>> maps = zijianJdbcTemplate.queryForList(sql);
            for(Map<String,Object> map : maps) {
                String priNum = (String)map.get("priNum");
                jdbcTemplate.update(delPrisonerMainSql,priNum);
                jdbcTemplate.update(delPrisonerFxSql,priNum);
                jdbcTemplate.update(delPrisonerSrSql,priNum);
                jdbcTemplate.update(delPrisonerZnSql,priNum);
                jdbcTemplate.update(delPrisonerHcSql,priNum);
            }
        } else {
            log.error("检测到数据源不可用,本次执行任务【删除撤回核查同步的记录】失败!");
        }
    }

    /**
     * 处理衔接接口
     * @param executeMainSql executeMainSql
     * @param executeFxSql executeFxSql
     * @param executeSrSql executeSrSql
     * @param executeZnSql executeZnSql
     * @param executeJxjsSql executeJxjsSql
     * @param executeZyjnSql executeZyjnSql
     * @param executeReceiptSql executeReceiptSql
     * @param xjReceiptDataSql xjReceiptDataSql
     * @param executeCjpgSql executeCjpgSql
     * @param executeXjxxSql executeXjxxSql
     * @param executeAbsql executeAbsql
     * @param executeXiaozuSql executeXiaozuSql
     * @param executeHcSql executeHcSql
     * @param priNum 罪犯编号
     * @param state state
     */
    private void executeZxxj(String executeMainSql,String prisaveTempSql,String executeFxSql,String executeSrSql,String executeZnSql,String executeJxjsSql,String executeZyjnSql,String executeReceiptSql,String xjReceiptDataSql,String executeCjpgSql,String executeXjxxSql,String executeAbsql,String executeXiaozuSql,String executeHcSql,String priNum,String state) {
        executezxhc(executeMainSql,prisaveTempSql,executeFxSql,executeSrSql,executeZnSql,executeHcSql,priNum);
        List<PrisonerJxjs> prisonerJxjs = zijianJdbcTemplate.query(executeJxjsSql,new BeanPropertyRowMapper<>(PrisonerJxjs.class),priNum);
        List<PrisonersZyjn> prisonersZyjns = zijianJdbcTemplate.query(executeZyjnSql,new BeanPropertyRowMapper<>(PrisonersZyjn.class),priNum);
        List<XjReceipt> xjReceipts = zijianJdbcTemplate.query(executeReceiptSql,new BeanPropertyRowMapper<>(XjReceipt.class),priNum);
        //回执消息表集合
        List<XjReceiptData> xjReceiptData = new ArrayList<>();
        for (int i = 0; i < xjReceipts.size(); i++) {
            String xjid = xjReceipts.get(i).getXjid();
            xjReceiptData = zijianJdbcTemplate.query(xjReceiptDataSql,new BeanPropertyRowMapper<>(XjReceiptData.class),xjid);
        }
        PrisonerCjpg prisonerCjpg = zijianJdbcTemplate.queryForObject(executeCjpgSql,new BeanPropertyRowMapper<>(PrisonerCjpg.class),priNum);
        PrisonerXjxx prisonerXjxx = zijianJdbcTemplate.queryForObject(executeXjxxSql,new BeanPropertyRowMapper<>(PrisonerXjxx.class),priNum);
        PrisonerHc prisonerHc = zijianJdbcTemplate.queryForObject(executeHcSql,new BeanPropertyRowMapper<>(PrisonerHc.class),priNum);
        //发起衔接时未保存ab_prisoners信息和小组信息(单独处理)
        if(StringUtils.equals(state,Constants.NumberStr.NUM_STR_FOUR)) {
            AbPrisonersResultVo abPrisonersResultVo = zijianJdbcTemplate.queryForObject(executeAbsql,new BeanPropertyRowMapper<>(AbPrisonersResultVo.class),priNum);
            AbXiaozuResultVo abXiaozuResultVo = zijianJdbcTemplate.queryForObject(executeXiaozuSql,new BeanPropertyRowMapper<>(AbXiaozuResultVo.class),priNum);
            //入库ab_prisoners信息
            if(null != abPrisonersResultVo) {
                abPrisonersResultVo.insertOrUpdate();
            }
            //入库ab_xiaozu信息
            if(null != abXiaozuResultVo) {
                assert abPrisonersResultVo != null;
                abPrisonersResultVo.insertOrUpdate();
            }
        }
        //入库prisoner_jxjs信息
        if(!CollectionUtils.isEmpty(prisonerJxjs)) {
            for(PrisonerJxjs prisonerJxj : prisonerJxjs) {
                prisonerJxj.insertOrUpdate();
            }
        }
        //入库prisoner_zyjn信息
        if(!CollectionUtils.isEmpty(prisonersZyjns)) {
            for(PrisonersZyjn prisonersZyjn : prisonersZyjns) {
                prisonersZyjn.insertOrUpdate();
            }
        }
        //入库xj_receipt信息
        if(!CollectionUtils.isEmpty(xjReceipts)) {
            for(XjReceipt xjReceipt : xjReceipts) {
                xjReceipt.insertOrUpdate();
            }
        }
        //入库xj_receipt_Data信息
        if(!CollectionUtils.isEmpty(xjReceiptData)) {
            for(XjReceiptData xjReceiptDatum : xjReceiptData) {
                xjReceiptDatum.insertOrUpdate();
            }
        }
        //入库prisoner_cjpg信息
        if(null != prisonerCjpg) {
            prisonerCjpg.insertOrUpdate();
        }
        //入库prisoner_xjxx信息
        if(null != prisonerXjxx) {
            prisonerXjxx.insertOrUpdate();
        }
        //入库prisoner_hc信息
        if(null != prisonerHc) {
            prisonerHc.insertOrUpdate();
        }
    }

    /**
     * 处理核查接口
     * @param executeMainSql executeMainSql
     * @param executeFxSql executeFxSql
     * @param executeSrSql executeSrSql
     * @param executeZnSql executeZnSql
     * @param executeHcSql executeHcSql
     * @param priNum priNum
     */
    private void executezxhc(String executeMainSql,String prisaveTempSql,String executeFxSql,String executeSrSql,String executeZnSql,String executeHcSql,String priNum) {
        PrisonerMain prisonerMain = zijianJdbcTemplate.queryForObject(executeMainSql,new BeanPropertyRowMapper<>(PrisonerMain.class),priNum);
        PrisaveTemp prisaveTemp = zijianJdbcTemplate.queryForObject(prisaveTempSql,new BeanPropertyRowMapper<>(PrisaveTemp.class),priNum);
        PrisonerFx prisonerFx = zijianJdbcTemplate.queryForObject(executeFxSql,new BeanPropertyRowMapper<>(PrisonerFx.class),priNum);
        List<PrisonerSr> prisonerSrs = zijianJdbcTemplate.query(executeSrSql,new BeanPropertyRowMapper<>(PrisonerSr.class),priNum);
        List<PrisonerZn> prisonerZns = zijianJdbcTemplate.query(executeZnSql,new BeanPropertyRowMapper<>(PrisonerZn.class),priNum);
        PrisonerHc prisonerHc = zijianJdbcTemplate.queryForObject(executeHcSql,new BeanPropertyRowMapper<>(PrisonerHc.class),priNum);
        //入库prisoner_main信息表
        if(null != prisonerMain) {
            prisonerMain.insertOrUpdate();
        }
        //入库prisoner_fx信息表
        if(null != prisonerFx) {
            prisonerFx.insertOrUpdate();
        }
        //入库prisoner_sr信息表
        if(!CollectionUtils.isEmpty(prisonerSrs)) {
            for(PrisonerSr prisonerSr : prisonerSrs) {
                prisonerSr.insertOrUpdate();
            }
        }
        //入库prisoner_zn信息表
        if(!CollectionUtils.isEmpty(prisonerZns)) {
            for(PrisonerZn prisonerZn : prisonerZns) {
                prisonerZn.insertOrUpdate();
            }
        }
        //入库prisave_temp四项信息录入状态表
        if (null != prisaveTemp) {
            prisaveTemp.insertOrUpdate();
        }
        //入库prisoner_hc信息表
        if(null != prisonerHc) {
            prisonerHc.insertOrUpdate();
        }
    }
}